package demos.modifysql;

import gudusoft.gsqlparser.EDbVendor;
import gudusoft.gsqlparser.TGSqlParser;
import gudusoft.gsqlparser.TStatementList;
import gudusoft.gsqlparser.nodes.TExpression;
import gudusoft.gsqlparser.stmt.TSelectSqlStatement;

import java.util.LinkedList;

/**
 * @author chen
 * @date 2023/8/1 16:34
 */
public class replaceTablenameFour {
    public static void main(String[] args) {
        TGSqlParser sqlparser = new TGSqlParser(EDbVendor.dbvmysql);
        sqlparser.sqltext = "SELECT `user`.name,\n       pow(floor(`order`.price),2) as calculated_price\nFROM   `user`,\n       `order`\nWHERE  `user`.id = `order`.uid";
        int ret = sqlparser.parse();
        if (ret == 0) {
            TStatementList stmts = sqlparser.getSqlstatements();
            TSelectSqlStatement stmt = (TSelectSqlStatement) stmts.get(0);

            // getResultColumn 获取 select 语句形成的 record set 中的 column
            stmt.getResultColumnList().forEach(column -> {
                if (column.getExpr().getFunctionCall() != null) {
                    LinkedList<String> list = new LinkedList<>();
                    TExpression expr = column.getExpr();
                    // 递归地获取函数参数
                    while (expr.getFunctionCall() != null) {
                        // 记录函数调用
                        list.addFirst(expr.getFunctionCall().getFunctionName().toString());
                        expr = expr.getFunctionCall().getArgs().getExpression(0);
                    }
                    list.addFirst(
                            String.format("%s(%s)",
                                    expr.toString().split("\\.")[1],
                                    expr.toString().split("\\.")[0]
                            )
                    );
                    list.add(String.format("%s(RS-1)", column.getDisplayName()));

                    System.out.println(String.join(" -> ", list) + "\n");
                } else {
                    System.out.printf("%s(%s) -> %s(RS-1)\n",
                            column.getDisplayName(),
                            column.getPrefixTable(),
                            column.getDisplayName()
                    );
                }
            });
        } else {
            System.out.println(sqlparser.getErrormessage());
        }
    }
}
